package com.nageoffer.onecoupon.merchant.admin.mq.producer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.nageoffer.onecoupon.merchant.admin.dao.entity.CouponTaskDO;
import com.nageoffer.onecoupon.merchant.admin.enums.CouponTaskStatusEnum;
import com.nageoffer.onecoupon.merchant.admin.mq.base.BaseSendExtendDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;

import java.util.Date;

@Slf4j(topic = "CommonSendProduceTemplate")
@RequiredArgsConstructor
public abstract  class AbstractCommonSendProduceTemplate<T> {
    private   final RocketMQTemplate rocketMQTemplate;

    protected abstract BaseSendExtendDTO buildBaseSendExtendParam(T messageSendEvent);

    protected abstract Message<?> buildMessage(T messageSendEvent, BaseSendExtendDTO requestParam);



    public SendResult  sendMessage(T messageSendEvent){
        BaseSendExtendDTO baseSendExtendDTO = buildBaseSendExtendParam(messageSendEvent);
        SendResult  sendResult;
        try {
            StringBuilder topic = StrUtil.builder().append(baseSendExtendDTO.getTopic());
            if (StrUtil.isNotBlank(baseSendExtendDTO.getTag())) {
                topic.append(":").append(baseSendExtendDTO.getTag());
            }


            if ( baseSendExtendDTO.getDelayTime()!= null){
                sendResult = rocketMQTemplate.syncSendDelayTimeMills
                               (topic.toString(),
                                buildMessage(messageSendEvent, baseSendExtendDTO),
                                baseSendExtendDTO.getDelayTime());
            }else {

                sendResult = rocketMQTemplate.syncSend(topic.toString(),
                                buildMessage(messageSendEvent, baseSendExtendDTO),
                                baseSendExtendDTO.getSentTimeout());
            }
            log.info("[生产者] {} - 发送结果：{}，消息ID：{}，消息Keys：{}", baseSendExtendDTO.getEventName(), sendResult.getSendStatus(), sendResult.getMsgId(), baseSendExtendDTO.getKeys());

        }catch ( Exception e){
            log.error("[生产者] {} - 消息发送失败，消息体：{}", baseSendExtendDTO.getEventName(), JSON.toJSONString(messageSendEvent), e);
            throw e;
        }
        return  sendResult;
    }
}
